package com.doctor.utils.network;


import android.content.Context;

import com.doctor.constants.CodeHelper;
import com.doctor.constants.NetConfig;
import com.doctor.ui.R;
import com.doctor.utils.callback.DownloadCompleteListener;
import com.doctor.utils.logutils.LogUtils;
import com.doctor.utils.sys.ToastUtils;
import com.google.gson.Gson;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.List;


/**
 * 网络请求工具类,这里重复代码,,等有时间要重构 by qy
 * Created by chemin on 2016/11/29.
 */
public class HttpManager {


    /**
     * @param context   上下文对象
     * @param url       请求地址
     * @param beanClass 数据模型类
     * @param listener  回调监听
     */
    public static <T> void okhttpGet(final Context context, String url, final Class<T> beanClass,
                                     final DownloadCompleteListener<T> listener) {
        if (!NetWorkReceiverUtils.getInstance().getNetwork()) {
            ToastUtils.showLongToast(context, NetConfig.NETWORK_BROKE);
            listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.NETWORK_BROKE);
            return;
        }
        LogUtils.i("get请求的url---" + url);
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                LogUtils.e("请求失败---" + e.toString());
            }

            @Override
            public void onResponse(String response) {
                LogUtils.i("get请求返回的数据---" + response);
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    String message = object.getString("message");
                    if (code == CodeHelper.RESPONSE_SUCCESS) {
                        Gson gson = new Gson();
                        listener.downLoadSuccess(gson.fromJson(response, beanClass));
                    } else {
                        listener.downLoadError(code, message);
                    }
                } catch (JSONException e) {
                    listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                    e.printStackTrace();
                }
            }
        });
    }




    /**
     * @param context  上下文
     * @param url      请求地址
     * @param paramKey 请求key
     * @param param    请求参数
     * @param listener 回调listener
     */
    public static <T> void okhttpPost(final Context context, String url, String paramKey, String
            param, final Class<T> objectClass, final DownloadCompleteListener<T> listener) {
        if (!NetWorkReceiverUtils.getInstance().getNetwork()) {
            ToastUtils.showLongToast(context, NetConfig.NETWORK_BROKE);
            listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.NETWORK_BROKE);
            return;
        }
        LogUtils.i("post请求的url---" + url);
        LogUtils.i("post请求的key===" + paramKey + ",--->param===" + param);
        OkHttpUtils.postString().url(url).content(param).addParams(paramKey, param).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                        LogUtils.e("请求失败---" + e.toString());
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtils.i("post请求的返回的数据---" + response);
                        try {
                            JSONObject object = new JSONObject(response);
                            int code = object.getInt("code");
                            String message = object.getString("message");
                            if (code == CodeHelper.RESPONSE_SUCCESS) {
                                if (objectClass != null) {
                                    Gson gson = new Gson();
                                    listener.downLoadSuccess(gson.fromJson(response, objectClass));
                                } else {
                                    listener.downLoadSuccess((T) message);
                                }
                            } else {
                                listener.downLoadError(code, message);
                            }
                        } catch (JSONException e) {
                            listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                            e.printStackTrace();
                        }
                    }
                });
    }


    /**
     * @param context  上下文
     * @param url      请求地址
     * @param paramKey 请求key
     * @param param    请求参数
     * @param listener 回调listener
     */
    public static <T> void okhttpSimplePost(final Context context, String url, String paramKey, String
            param, final DownloadCompleteListener<T> listener) {
        if (!NetWorkReceiverUtils.getInstance().getNetwork()) {
            ToastUtils.showLongToast(context, NetConfig.NETWORK_BROKE);
            if (listener != null) {
                listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.NETWORK_BROKE);
            }
            return;
        }
        LogUtils.i("post请求的url---" + url);
        LogUtils.i("post请求的key===" + paramKey + ",--->param===" + param);
        OkHttpUtils.postString().url(url).content(param).addParams(paramKey, param).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        if (listener != null) {
                            listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                        }
                        LogUtils.e("请求失败---" + e.toString());
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtils.i("postSimple请求的返回的数据---" + response);
                        try {
                            JSONObject object = new JSONObject(response);
                            int code = object.getInt("code");
                            String message = object.getString("message");
                            if (code == CodeHelper.RESPONSE_SUCCESS) {
                                if (listener != null) {
                                    listener.downLoadSuccess((T) message);
                                }
                            } else {
                                if (listener != null) {
                                    listener.downLoadError(code, message);
                                }
                            }
                        } catch (JSONException e) {
                            if (listener != null) {
                                listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                            }
                            e.printStackTrace();
                        }
                    }
                });
    }

    /**
     * @param context     上下文
     * @param url         请求地址
     * @param paramKey    请求key
     * @param fileName    上传的文件名
     * @param file        上传的文件
     * @param objectClass 返回参数的been类
     * @param listener    回调listener
     */
    public static <T> void okhttpPostFile(final Context context, String url, String paramKey, String
            fileName, File file, final Class<T> objectClass, final DownloadCompleteListener<T> listener) {
        if (!NetWorkReceiverUtils.getInstance().getNetwork() && context != null) {
            String tip = NetConfig.NETWORK_BROKE;
            ToastUtils.showLongToast(context, tip);
            listener.downLoadError(CodeHelper.NETWORK_ERROR, tip);
            return;
        }
        LogUtils.i("post请求的url---" + url);
        OkHttpUtils.post().url(url).addFile(paramKey, file.getName(), file).build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Request request, Exception e) {
                        listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                        LogUtils.e("请求失败---" + e.toString());
                    }

                    @Override
                    public void onResponse(String response) {
                        LogUtils.i("postFile请求的返回的数据---" + response);
                        try {
                            JSONObject object = new JSONObject(response);
                            int code = object.getInt("code");
                            String message = object.getString("message");
                            if (code == CodeHelper.RESPONSE_SUCCESS) {
                                Gson gson = new Gson();
                                listener.downLoadSuccess(gson.fromJson(response, objectClass));
                            } else {
                                listener.downLoadError(code, message);
                            }
                        } catch (JSONException e) {
                            listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                            e.printStackTrace();
                        }
                    }
                });
    }


    /**
     * @param context 上下文
     * @param url     请求地址
     */
    public static void okhttpPostFile(final Context context, String url, List<String> images, String paramKey, String musicUuid, final DownloadCompleteListener listener) {
//        if (!NetWorkReceiverUtils.getInstance().getNetwork() && context != null) {
//            String tip = NetConfig.NETWORK_BROKE;
//            ToastUtils.showLongToast(context, tip);
//            listener.downLoadError(CodeHelper.NETWORK_ERROR, tip);
//            return;
//        }
//        okhttp3.MediaType MEDIA_TYPE_PNG = okhttp3.MediaType.parse("image/png");
//        OkHttpClient okHttpClient = new OkHttpClient();
//        MultipartBody.Builder builder = new MultipartBody.Builder().setType(MultipartBody.FORM);
//        for (int i = 0; i < images.size(); i++) {
//            String imagePath = images.get(i);
//            File file = new File(imagePath);
//            if (file != null) {
//                builder.addFormDataPart(FormInfoConfig.FILES, file.getName(), okhttp3.RequestBody.create(MEDIA_TYPE_PNG, file));
//            }
//        }
//
//        LogUtils.e("url---" + url);
//        builder.addFormDataPart(FormInfoConfig.UUID, user.getUuid());
//        builder.addFormDataPart(paramKey, musicUuid);
//        final MultipartBody build = builder.build();
//
//        //构建请求
//        final okhttp3.Request request = new okhttp3.Request.Builder()
//                .url(url)
//                .post(build)
//                .build();
//        okHttpClient.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                LogUtils.e("上传文件失败-----");
//                listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
//            }
//
//            @Override
//            public void onResponse(Call call, Response response) throws IOException {
//                LogUtils.e("上传文件返回-----code==" + response.code());
//                if (response.code() == 200) {
//                    String res = response.body().string();
//                    try {
//                        JSONObject object = new JSONObject(res);
//                        int code = object.getInt("code");
//                        String message = object.getString("message");
//                        LogUtils.e("上传文件返回的数据----" + res);
//                        if (code == 0) {
//                            listener.downLoadSuccess(res);
//                        } else {
//                            listener.downLoadError(code, message);
//                        }
//                    } catch (JSONException e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        });
    }


    /**
     * 直接接字符串的  不进行初始解析的请求,,,这里重复代码,,等有时间要重构 by qy
     *
     * @param context
     * @param url
     * @param listener
     */
    public static void okHttpGetString(final Context context, String url, final
    DownloadCompleteListener<String> listener) {
        if (!NetWorkReceiverUtils.getInstance().getNetwork()) {
            ToastUtils.showLongToast(context, context.getString(R.string.net_work_error));
            listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.NETWORK_BROKE);
            return;
        }
        LogUtils.i("get请求的url---" + url);
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {
                listener.downLoadError(CodeHelper.NETWORK_ERROR, NetConfig.LOADING_ERROR);
                LogUtils.e("请求失败---" + e.toString());
            }

            @Override
            public void onResponse(String response) {
                listener.downLoadSuccess(response);
                LogUtils.d("请求结果字符串-----:");
            }
        });
    }

}
